package com.example.proxy;

import com.example.annotation.Transactional;
import com.example.manager.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JdkTransactionHandler implements InvocationHandler {
    private final Object target;
    
    public JdkTransactionHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //
        if (method.isAnnotationPresent(Transactional.class) ||
            method.getDeclaringClass().isAnnotationPresent(Transactional.class)) {
            try {
                TransactionManager.begin();
                Object result = method.invoke(target, args);
                TransactionManager.commit();
                return result;
            } catch (Exception e) {
                TransactionManager.rollback();
                throw e;
            }
        }
        return method.invoke(target, args);
    }
}